package com.hkyl.hospital.web.controller;

import com.hkyl.hospital.domain.ResultVo;
import com.hkyl.hospital.entity.Permission;
import com.hkyl.hospital.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
/**
 * @author hyh
 * @date 2023/07/10 14:58:05
 */
@RestController
@RequestMapping("permission")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    @PostMapping("root")
    public ResultVo getRoot() {
        return ResultVo.success(permissionService.getRoot());
    }

    @PostMapping("save")
    public ResultVo save(@RequestBody Permission permission) {
        return permissionService.save(permission) > 0 ? ResultVo.success("添加成功", permission)
                : ResultVo.failure("添加失败");
    }

    @PostMapping("update")
    public ResultVo update(@RequestBody Permission permission) {
        return permissionService.update(permission) > 0 ? ResultVo.success("修改成功")
                : ResultVo.failure("修改失败");
    }

    @PostMapping("delete")
    public ResultVo remove(@RequestBody String permissionId) {
        if (!StringUtils.hasText(permissionId))
            throw new RuntimeException("permissionId is null");
        return permissionService.remove(Integer.valueOf(permissionId)) > 0 ? ResultVo.success("删除成功")
                : ResultVo.failure("删除失败");
    }

    @PostMapping("permissionByRole")
    public ResultVo permissionByRoleId(@RequestBody String roleId) {
        if (!StringUtils.hasText(roleId))
            throw new RuntimeException("permissionId is null");
        return ResultVo.success(permissionService.getPermissionByRoleId(Integer.valueOf(roleId)));
    }

    @PostMapping("distributePermissions")
    public ResultVo distributePermissions(@RequestBody Map map) {
        Integer roleId = (Integer) map.get("roleId");
        List<Integer> permissionIds = (List<Integer>) map.get("permissionIds");
        return permissionService.distributePermissions(roleId, permissionIds) > 0 ? ResultVo.success("分配成功")
                : ResultVo.success("无效分配");
    }
}
